#include "HPnumber.h"

void strrec(Int left, Int right) {
    while (left < right) {
        char tmp = *left;
        *left = *right;
        *right = tmp;
        left++;
        right--;
    }
}

Int IntWrite(Int data) {
    int lenth = strlen(data);
    for (int i = 0; i < lenth; i++)
        if (data[i] > '9' || data[i] < '0') return NULL;
    char *tmp = calloc(sizeof(char), lenth + 1);
    strcpy(tmp, data);
    strrec(tmp, tmp + lenth - 1);
    return tmp;
}

int putInt(Int num) {
    int lenth = strlen(num);
    for (int i = lenth - 1; i >= 0; --i)
        printf("%c", *(num + i));
    printf("\n");
    return lenth;
}

Int IntAdd(Int num1, Int num2) {
    int len1 = strlen(num1);
    int len2 = strlen(num2);
    Int add = calloc(sizeof(char), len1 > len2 ? len1 + 2 : len2 + 2);
    if (!add) return NULL;
    int lenth = len1 > len2 ? len1 + 1 : len2 + 1;
    for (int i = 0; i < len1; ++i)
        *(add + i) += *(num1 + i) - '0';
    for (int i = 0; i < len2; ++i)
        *(add + i) += *(num2 + i) - '0';
    for (int i = 0; i < lenth; ++i) {
        if (i >= lenth - 1 && *(add + i) == 0) break;
        if (*(add + i) > 9) {
            *(add + i) -= 10;
            *(add + i + 1) += 1;
        }
        *(add + i) += '0';
    }
    return add;
}

Int IntMul(Int num1, Int num2) {
    int len1, len2;
    len1 = IntLent_int(num1);
    len2 = IntLent_int(num2);
    int lenth = (len1 * len2 + 2) + ((len2 * len1 ) >> 1);
    Int mul = calloc(sizeof(char), lenth);
    for (int i = 0; i < len1; ++i) {
        for (int j = 0; j < len2; ++j) {
            *(mul + i + j + 1) += *(num1 + i) * *(num2 + j) / 10;
            if (*(mul + i + j + 1) < '0') *(mul + i + j + 1) += '0';
            *(mul + i + j) += *(num1 + i) * *(num2 + j) % 10;
            if(*(mul + i + j) < '0') *(mul + i + j) += '0';
            else if (*(mul + i + j) > '9'){
                *(mul + i + j) -= 10;
                *(mul + i + j + 1) += 1;
            }
            if (*(mul + i + j) > '9'){
                *(mul + i + j) -= 10;
                *(mul + i + j + 1) += 1;
            }
        }
    }
    lenth = strlen(mul);
    if (* (mul + lenth - 1) == '0') * (mul + lenth - 1) = 0;
    return mul;
}

int IntLent_int(Int num) {
    int len = 0;
    while (*(num + len) != 0) {
        *(num + len) -= '0';
        len++;
    }
    return len;
}

int main() {
//    Int lnumI = IntWrite("123456789");;
//    putInt(lnumI);
//    Int num0 = IntWrite("987654321");
//    putInt(num0);
//    Int d = IntAdd("0", num0);
    long long z = 987654321;
    long long x = 123456789;
    printf("%lld\n",z*x);
    Int num1 = IntWrite("10");
    Int num2 = IntWrite("1");
    Int c = IntMul(num2, num1);
    putInt(c);
}